package top.fyukina.fyson;

import top.fyukina.fyson.runtime.exception.IllegalFileException;
import top.fyukina.fyson.runtime.loader.JSONLoader;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

public final class Main {
    private Main() {}
    public static void main(String[] args) throws Exception {
        if (args == null || args.length == 0) System.exit(0);
        File f = new File(args[0]);
        if (!f.exists()) throw new FileNotFoundException(f.getPath());
        String ext;
        try {
            ext = f.getName().substring(f.getName().lastIndexOf('.'));
        } catch (StringIndexOutOfBoundsException e) {
            ext = "";
        }
        try {
            if (".json".equalsIgnoreCase(ext)) JSONLoader.load(read(f));
            else throw new IllegalFileException(f.getPath());
        } catch (Exception e) {
            System.err.println("> Exception (" + e.getClass().getName() + ") occurred:\n\t"
                    + e.getMessage().replaceAll("\n", "\n\t"));
            System.exit(-1);
        }
    }
    private static String read(File file) throws Exception {
        BufferedReader r = new BufferedReader(new FileReader(file));
        StringBuilder t = new StringBuilder();
        String line;
        while ((line = r.readLine()) != null)
            t.append(line).append("\n");
        return t.toString();
    }
}